import React, { useState } from 'react';
import { useDropzone } from 'react-dropzone';
import axios from 'axios';
import '../css/ImageUpload.css';

const FundusImageUpload = () => {
  const selectedModel = '6 Sınıflı Xception';
  const [fileItems, setFileItems] = useState([]);
  const [isLoading, setIsLoading] = useState(false);

  const { getRootProps, getInputProps } = useDropzone({
    accept: 'image/jpeg, image/png',
    multiple: true,
    onDrop: (acceptedFiles) => {
      setFileItems([]);
      acceptedFiles.forEach((file) => {
        const preview = URL.createObjectURL(file);
        resizeImage(file, (resizedFile) => {
          const newItem = {
            file: resizedFile,
            preview: preview,
            prediction: null,
            time: new Date().toLocaleString(),
          };
          setFileItems((prev) => [...prev, newItem]);
        });
      });
    },
  });

  const resizeImage = (file, callback) => {
    const reader = new FileReader();
    reader.onload = (event) => {
      const img = new Image();
      img.src = event.target.result;
      img.onload = () => {
        const canvas = document.createElement('canvas');
        const ctx = canvas.getContext('2d');
        const maxSize = 800;
        let width = img.width;
        let height = img.height;
        if (width > height) {
          if (width > maxSize) {
            height *= maxSize / width;
            width = maxSize;
          }
        } else {
          if (height > maxSize) {
            width *= maxSize / height;
            height = maxSize;
          }
        }
        canvas.width = width;
        canvas.height = height;
        ctx.drawImage(img, 0, 0, width, height);
        canvas.toBlob(callback, 'image/jpeg', 1);
      };
    };
    reader.readAsDataURL(file);
  };

  const handleUpload = async () => {
    if (fileItems.length === 0) {
      alert('请先选择至少一张图片');
      return;
    }

    setIsLoading(true);
    const updatedItems = [];

    for (let i = 0; i < fileItems.length; i++) {
      const { file, preview, time } = fileItems[i];
      const formData = new FormData();
      formData.append('file', file, `image_${i}.jpg`);

      let predictionResult = null;
      try {
        const response = await axios.post('http://localhost:7860/predict', formData, {
          headers: { 'Content-Type': 'multipart/form-data' },
        });
        const result = response.data[selectedModel];
        predictionResult = `${result.class}（概率: ${(result.probability * 100).toFixed(2)}%）`;
      } catch (error) {
        console.error('预测失败:', error);
        predictionResult = '预测失败';
      }

      updatedItems.push({
        file,
        preview,
        prediction: predictionResult,
        time,
      });
    }

    setFileItems(updatedItems);
    setIsLoading(false);
  };

  const handleClear = () => {
    setFileItems([]);
  };

  return (
    <div className="upload-container">
      <h2 className="title">眼底图像检测</h2>

      <div className="button-group">
        <div {...getRootProps()}>
          <input {...getInputProps()} />
          <button type="button" className="select-button">选择图片</button>
        </div>

        <button onClick={handleUpload} className="upload-button" disabled={isLoading}>
          {isLoading ? '正在预测...' : '开始预测'}
        </button>

        {fileItems.length > 0 && (
          <button onClick={handleClear} className="clear-button">清空</button>
        )}
      </div>

      {fileItems.length > 0 && (
        <div className="table-container">
          <table className="preview-table">
            <thead>
              <tr>
                <th>图片预览</th>
                <th>预测结果</th>
                <th>检测时间</th>
              </tr>
            </thead>
            <tbody>
              {fileItems.map((item, index) => (
                <tr key={index}>
                  <td>
                    <img src={item.preview} alt={`preview-${index}`} className="image-preview" />
                  </td>
                  <td>{item.prediction || '尚未预测'}</td>
                  <td>{item.time}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
};

export default FundusImageUpload;
